package com.gzhryc.shared_device.oem.h5.mng.controllers.bxscn;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.MatrixToImageWriter;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyCabinet;
import com.gzhryc.shared_device.bxscn.code.dao.db.PortableEnergyCabinetSlot;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyCabinetService;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyCabinetSlotService;
import com.gzhryc.shared_device.bxscn.code.services.dto.PortableEnergyCabinetSearch;
import com.gzhryc.shared_device.cdb.code.dao.enums.BatteryCabinetEnum;
import com.gzhryc.shared_device.common.device.dao.db.Device;
import com.gzhryc.shared_device.common.device.dao.db.DeviceType;
import com.gzhryc.shared_device.common.device.dao.db.DeviceTypeFunc;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeFuncService;
import com.gzhryc.shared_device.common.device.services.DeviceTypeService;
import com.gzhryc.shared_device.iot.code.dao.db.IOTServerNode;
import com.gzhryc.shared_device.iot.code.services.IOTServerNodeService;
import com.gzhryc.shared_device.oem.code.device.EDeviceFunCode;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.oem.h5.mng.dto.bxscn.PortableEnergyCabinetData;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PortableEnergyCabinetController {

    static Logger log = Logger.getLogger(PortableEnergyCabinetController.class);

    @Route("/bxscn/device/list.html")
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList", BatteryCabinetEnum.State.values());
        List<String> deviceTypeIds = DeviceTypeFuncService.self().findTypeIdByCode(EDeviceFunCode.BXSCN.index());
        List<DeviceType> deviceTypeList = DeviceTypeService.self().findByIds(deviceTypeIds);
        if(deviceTypeList != null){
            request.setAttribute("deviceTypeList", deviceTypeList);
        }
        return "/bxscn/device/list.html";
    }

    @Route(value = "/bxscn/device/list.data")
    public ListResult<PortableEnergyCabinetData> listData(HttpServletRequest request) {
        ListResult<PortableEnergyCabinetData> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        PortableEnergyCabinetSearch search = WebUtils.getParameter(request, PortableEnergyCabinetSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(PortableEnergyCabinetService.self().countJoinBySearch(search));
        List<PortableEnergyCabinet> batteryCabinetList = PortableEnergyCabinetService.self().findJoinBySearch(search, pageNo, pageLimit);
        if (batteryCabinetList != null && batteryCabinetList.size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(new ArrayList<>());

            for (PortableEnergyCabinet portableEnergyCabinet : batteryCabinetList) {
                PortableEnergyCabinetData item = ClassTools.copy(new PortableEnergyCabinetData(), portableEnergyCabinet);
                IOTServerNode serverNode = IOTServerNodeService.self().getById(portableEnergyCabinet.getIotNodeId());
                if (serverNode != null) {
                    item.setIotNodeName(serverNode.getName());
                } else if (portableEnergyCabinet.getIotNodeId() != null) {
                    item.setIotNodeName(portableEnergyCabinet.getIotNodeId().toString());
                }
                result.getBody().getData().add(item);
            }
        }
        return result;
    }

    @Route("/bxscn/device/add.html")
    public String add(HttpServletRequest request) {
        List<DeviceType> deviceTypeList = DeviceTypeService.self().findAll();
        request.setAttribute("deviceTypeList", deviceTypeList);
        List<IOTServerNode> iotNodeList = IOTServerNodeService.self().findAllUnable();
        request.setAttribute("iotNodeList", iotNodeList);
        return "/bxscn/device/edit.html";
    }

    @Route(value = {"/bxscn/device/add.do"})
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增便携式电池充电柜失败");
        PortableEnergyCabinet portableEnergyCabinet = WebUtils.getParameter(request, PortableEnergyCabinet.class);
        try {
            DeviceType deviceType = DeviceTypeService.self().getById(portableEnergyCabinet.getDeviceTypeId());
            if(deviceType == null){
                result.setMsg("设备类型不存在");
                return result;
            }

            DeviceTypeFunc deviceTypeFunc = DeviceTypeFuncService.self()
                    .getByKeys(portableEnergyCabinet.getDeviceTypeId(), EDeviceFunCode.BXSCN.index());
            if (deviceTypeFunc == null) {
                result.setMsg("设备类型不存在此功能");
                return result;
            }
            portableEnergyCabinet.setDeviceTypeName(deviceType.getName());
            portableEnergyCabinet.setProtocolType(deviceTypeFunc.getProtocolType());
            if (PortableEnergyCabinetService.self().add(portableEnergyCabinet)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route("/bxscn/device/info.html")
    public String info(HttpServletRequest request) {
        String deviceSn = WebUtils.getString(request,"deviceSn");
        PortableEnergyCabinet portableEnergyCabinet = PortableEnergyCabinetService.self().getByDeviceSn(deviceSn);
        if(portableEnergyCabinet != null) {
            WebUtils.setAttribute(request, portableEnergyCabinet);

            Device device = DeviceService.self().getByDeviceSn(portableEnergyCabinet.getDeviceSn());
            if(device != null){
                request.setAttribute("device",device);
            }
        }
        return "/bxscn/device/info.html";
    }

    @Route(value = "/bxscn/device/slot/list.data")
    public ListResult<PortableEnergyCabinetSlot> slotListData(HttpServletRequest request) {
        ListResult<PortableEnergyCabinetSlot> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        String deviceSn = WebUtils.getString(request, "deviceSn");
        PortableEnergyCabinet portableEnergyCabinet = PortableEnergyCabinetService.self().getByDeviceSn(deviceSn);
        if (portableEnergyCabinet != null) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(new ArrayList<>());
            List<PortableEnergyCabinetSlot> slotList = PortableEnergyCabinetSlotService.self().findJoinByDeviceSn(deviceSn);

            for (int i = 1; i <= portableEnergyCabinet.getSlotTotal(); i++) {
                PortableEnergyCabinetSlot slot = null;
                if (slotList != null && slotList.size() > 0) {
                    for (PortableEnergyCabinetSlot item : slotList) {
                        if (item.getSlotNum().equals(i)) {
                            slot = item;
                            break;
                        }
                    }
                }
                if (slot == null) {
                    slot = new PortableEnergyCabinetSlot();
                    slot.setDeviceSn(deviceSn);
                    slot.setSlotNum(i);
                }
                result.getBody().getData().add(slot);
            }
        }
        return result;
    }

    @Route(value = { "/bxscn/device/qrcode.html" })
    public String qrcode(HttpServletRequest request) {
        String deviceSn = WebUtils.getString(request, "deviceSn");
        if (StringTools.isNotBlank(deviceSn)) {
            PortableEnergyCabinet portableEnergyCabinet = PortableEnergyCabinetService.self().getByDeviceSn(deviceSn);
            if (portableEnergyCabinet != null) {
                String httpDomain = PropertyTools.get().getString("httpDomain");
                String url = httpDomain + "/dev/bxscn/" + portableEnergyCabinet.getDeviceSn();
                request.setAttribute("url", url);
            }
        }
        return "/bxscn/device/qrcode.html";
    }

    @Route(value = { "/bxscn/device/qrcode.jpg" })
    public void qrcodeImg(HttpServletRequest request, HttpServletResponse response) {
        String deviceSn = WebUtils.getString(request, "deviceSn");
        if (StringTools.isNotBlank(deviceSn)) {
            PortableEnergyCabinet portableEnergyCabinet = PortableEnergyCabinetService.self().getByDeviceSn(deviceSn);
            if (portableEnergyCabinet != null) {
                try {
                    String httpDomain = PropertyTools.get().getString("httpDomain");
                    String url = httpDomain + "/dev/bxscn/" + portableEnergyCabinet.getDeviceSn();
                    WebUtils.exportJPEG(response);
                    MatrixToImageWriter.writeToStream(url, 400, 300, "jpeg", response.getOutputStream());
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @Route(value = { "/bxscn/device/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除充电插座主机失败");
        String deviceSn = WebUtils.getString(request,"deviceSn");
        if(StringTools.isNotBlank(deviceSn)) {
            try {
                Device device = DeviceService.self().getByDeviceSn(deviceSn);
                if(device != null){
                    //检查设备类型对应的功能项
                    List<DeviceTypeFunc> deviceTypeFuncList = DeviceTypeFuncService.self().findByTypeId(device.getDeviceTypeId());
                    if(deviceTypeFuncList != null && deviceTypeFuncList.size() > 1) {
                        throw new LogicException("设备有"+deviceTypeFuncList.size()+"个功能项，请在设备索引列表中删除");
                    }
                    if(DeviceService.self().deleteByDeviceSn(deviceSn)){
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }else {
                    if (PortableEnergyCabinetService.self().deleteByDeviceSn(deviceSn)) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }
}
